package router

import (
	"fmt"
	"strings"

	// "gin-learning/routes/home"
	"os"
	"path/filepath"
	// "strings"
	"github.com/gin-gonic/gin"
	// "gin-learning/lib"
)

// func (r *cls.Route) Init(r_engine *gin.Engine) {
// 	for i := 0; i < len(r.routes); i++ {
// 		r.routes[i]
// 	}
// }

//路由分组记录
var groupRecord map[string]*gin.RouterGroup

/* 得到最末一级路由分组
 *
 */
func theGroup(onion []string) *gin.RouterGroup {
	router := gin.Default()

	var gPath string
	var tGroup *gin.RouterGroup
	var ok bool

	// 从最内层,逐个创建并记录分组，直到最内层分组, 或一层级下已存在分组，则结束
	for i := len(onion) - 1; i > 0; i-- {
		gPath += "/" + onion[i]
		tGroup, ok = groupRecord[gPath]
		fmt.Println("ok===>", ok)
		if !ok {
			tGroup = router.Group(gPath)
			groupRecord[onion[i]] = tGroup
		} else {
			return tGroup
		}
	}
	return tGroup
}

func init() {
	//router := gin.Default()
	os.Chdir("routes")
	pwd, _ := os.Getwd()

	//获取当前目录下的所有文件或目录信息
	filepath.Walk(pwd, func(path string, info os.FileInfo, err error) error {
		// fmt.Println(path) //打印path信息
		//fmt.Println(info.Name()) //打印文件或目录名
		//group = router.Group("/v1")
		if !info.IsDir() && !strings.Contains(path, "init.go") {
			//fmt.Println(info.Name())
			//fmt.Println(path) //打印path信息
			//fmt.Println(pwd)
			dotIndex := strings.Index(path, ".")
			path = path[len(pwd)+1 : dotIndex]
			onion := strings.Split(path, "\\")
			routeName := onion[len(onion)-1]

			fmt.Println("routeName: " + routeName)
			rPath := onion[0 : len(onion)-1]
			theGroup(rPath)
			theRoute := theGroup(rPath)
			theRoute.GET("/"+routeName, func(c *gin.Context) {
				c.JSON(200, gin.H{
					"message": "pong",
				})
			})
		}
		return nil
	})
}
